package com.galen.manual.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.galen.manual.entity.Admin;
import com.galen.manual.entity.User;
import com.galen.manual.mapper.AdminMapper;
import com.galen.manual.mapper.UserMapper;
import com.galen.manual.service.DataInitService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 数据初始化服务实现类
 * 应用启动时自动初始化必要的数据
 */
@Slf4j
@Service
@RequiredArgsConstructor
@Order(1) // 设置启动顺序
public class DataInitServiceImpl implements DataInitService, CommandLineRunner {

    private final UserMapper userMapper;
    private final AdminMapper adminMapper;
    private final BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

    @Override
    public void run(String... args) throws Exception {
        log.info("开始初始化应用数据...");
        initializeData();
        log.info("应用数据初始化完成");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void initializeData() {
        try {
            // 初始化超级管理员
            initializeSuperAdmin();

            log.info("超级管理员数据初始化完成");
        } catch (Exception e) {
            log.error("数据初始化失败", e);
            throw e;
        }
    }

    /**
     * 初始化超级管理员
     */
    private void initializeSuperAdmin() {
        // 检查是否已存在超级管理员
        QueryWrapper<Admin> adminQuery = new QueryWrapper<>();
        adminQuery.eq("role", "super");
        Admin existingAdmin = adminMapper.selectOne(adminQuery);

        if (existingAdmin != null) {
            log.info("超级管理员已存在，跳过初始化");
            return;
        }

        log.info("开始创建超级管理员...");

        // 创建用户
        User superAdminUser = new User();
        superAdminUser.setUsername("admin");
        superAdminUser.setPhone("17722515203");
        superAdminUser.setPassword(passwordEncoder.encode("admin123")); // 默认密码
        superAdminUser.setNickname("超级管理员");
        superAdminUser.setRealName("超级管理员");
        superAdminUser.setUserLevel(3);
        superAdminUser.setStatus(1);
        superAdminUser.preInsert(); // 调用preInsert生成ID

        userMapper.insert(superAdminUser);

        // 创建管理员记录
        Admin superAdmin = new Admin();
        superAdmin.setUserId(superAdminUser.getId());
        superAdmin.setRole("super");
        superAdmin.setStatus(1);
        superAdmin.preInsert(); // 调用preInsert生成ID

        adminMapper.insert(superAdmin);

        log.info("超级管理员创建成功，用户名: admin, 密码: admin123");
    }

  }